package com.baozun.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.commons.lang.StringUtils;

import com.baozun.model.TUser;
import com.baozun.model.TUserExample;

/**
 * 将obj组装成T
 *
 * @Title:
 * @Company:宝尊电子商务有限公司
 * @Description:
 * @Author:xiaozhou.zhou
 * @Since:2015年2月2日
 * @Copyright:Copyright (c) 2014
 * @ModifyDate:
 * @Version:1.1.0
 */
public class ModelExampleUtil {

    /**
     * 
     * @param obj
     * @param clazz
     * @return
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @throws NoSuchMethodException
     * @throws SecurityException
     * @throws InvocationTargetException
     * @throws ClassNotFoundException
     * @Description:
     */
    public static <T> T getCriteriaByModel(Object obj, Class<T> clazz) throws IllegalArgumentException, IllegalAccessException, InstantiationException, NoSuchMethodException, SecurityException, InvocationTargetException, ClassNotFoundException {
        Field[] fields = obj.getClass().getFields();// 只得到静态属性
        T t = clazz.newInstance();
        for (Field field : fields) {
            String fieldName = field.getName();
            StringBuffer methodName = new StringBuffer("and");
            StringBuffer propName = new StringBuffer();
            int index = 0;
            for (char ch : fieldName.toCharArray()) {
                // 第一个大写
                if (index == 0) {
                    propName.append((ch + "").toUpperCase());
                } else if ('_' == ch) {
                    index = -1;// index重新记数
                } else {
                    propName.append((ch + "").toLowerCase());
                }
                index++;
            }
            Object propValue = obj.getClass().getMethod("get" + propName).invoke(obj);
            if (propValue != null) {
                // 得到Crite中的方法
                methodName.append(propName).append("EqualTo");
                // 如果不为空，将运行clazz的固定方法
                String firstChar = fieldName.substring(0, 1);
                fieldName = fieldName.replace(firstChar, StringUtils.upperCase(firstChar));
                Method m = clazz.getMethod(methodName.toString(), String.class);
                m.invoke(t, propValue);
            }
        }
        return t;
    }
}
